JavaScript String and It's Methods
JavaScript String and It's Methods:
Introduction to String Data Type
In JavaScript, a string is a sequence of characters used to represent text. Strings are one of the six primitive data types in JavaScript. Strings can be enclosed in single (' '), double (" "), or backticks (` `) to create template literals.
let singleQuoteStr = 'Hello, World!';
let doubleQuoteStr = "Hello, JavaScript!";
let templateLiteralStr = `Hello, ${name}!`; // using template literals
Strings are immutable, meaning once created, they cannot be changed directly.
Strings can be created using string literals or the String() constructor.
Do You Know?
JavaScript strings are Unicode-based, supporting a wide range of characters from different languages.
String Methods
JavaScript provides a rich set of built-in methods to manipulate strings. Let's explore some of the most commonly used methods.
length
The length property returns the number of characters in a string.
let str = 'JavaScript';
console.log(str.length); // 10
charAt()
The charAt(index) method returns the character at the specified index in a string (0-based index).
let str = 'JavaScript';
console.log(str.charAt(4)); // S
toUpperCase() and toLowerCase()
toUpperCase() converts a string to uppercase.
toLowerCase() converts a string to lowercase.
let str = 'JavaScript';
console.log(str.toUpperCase()); // JAVASCRIPT
console.log(str.toLowerCase()); // javascript
indexOf()
The indexOf(substring) method returns the index of the first occurrence of the substring in the string. If not found, it returns -1.
let str = 'Learn JavaScript';
console.log(str.indexOf('JavaScript')); // 6
console.log(str.indexOf('Python')); // -1
slice()
The slice(startIndex, endIndex) method extracts a section of a string and returns it as a new string. The endIndex is optional and non-inclusive.
let str = 'JavaScript';
console.log(str.slice(0, 4)); // Java
console.log(str.slice(4)); // Script
substring()
The substring(startIndex, endIndex) method is similar to slice() but doesn't accept negative indices.
let str = 'JavaScript';
console.log(str.substring(0, 4)); // Java
console.log(str.substring(4)); // Script
replace()
The replace(oldValue, newValue) method replaces the first occurrence of a substring with a new value. To replace all occurrences, a regular expression with the global flag (g) is used.
let str = 'I love JavaScript';
console.log(str.replace('JavaScript', 'coding')); // I love coding
split()
The split(separator) method splits a string into an array of substrings, based on the specified separator.
let str = 'JavaScript is fun';
console.log(str.split(' ')); // ['JavaScript', 'is', 'fun']
trim()
The trim() method removes whitespace from both sides of a string.
let str = ' Hello, World! ';
console.log(str.trim()); // 'Hello, World!'
includes()
The includes(substring) method checks if a string contains the specified substring. It returns true or false.
let str = 'JavaScript is awesome!';
console.log(str.includes('JavaScript')); // true
console.log(str.includes('Python')); // false
startsWith() and endsWith()
startsWith(substring) checks if the string starts with the specified substring.
endsWith(substring) checks if the string ends with the specified substring.
let str = 'JavaScript is great!';
console.log(str.startsWith('Java')); // true
console.log(str.endsWith('great!')); // true
Important Note
JavaScript string methods generally do not modify the original string. They return a new string with the modifications.
Template Literals
Template literals provide an easier way to work with strings. They allow for multi-line strings, string interpolation, and embedded expressions.
let name = 'John';
let message = `Hello, ${name}! Welcome to JavaScript.`;
console.log(message); // Hello, John! Welcome to JavaScript.
Multi-line Strings
With template literals, you can create multi-line strings without using the newline escape sequence (\n).
let poem = `Roses are red,
Violets are blue,
JavaScript is fun,
And so are you!`;
console.log(poem);
String Interpolation
Template literals allow you to embed variables and expressions within strings using the ${} syntax.
let age = 30;
let greeting = `Happy ${age}th birthday!`;
console.log(greeting);
Embedded Expressions
You can also embed complex expressions within template literals.
let num1 = 10;
let num2 = 5;
let result = `The sum of ${num1} and ${num2} is ${num1 + num2}`;
console.log(result);
Escape Sequences
Escape sequences allow you to include special characters in strings. Common escape sequences include:
- \n: Newline
- \': Single quote
- \": Double quote
- \\: Backslash
let str = 'This is a new line:
And this is on the next line.';
console.log(str);
String Comparison
Strings in JavaScript can be compared using the comparison operators (==, ===, !=, etc.). String comparison is case-sensitive.
console.log('abc' === 'abc'); // true
console.log('abc' === 'ABC'); // false
Avoid This
Be cautious when using the loose equality operator (==) for comparing strings, as it can lead to unexpected results due to type coercion.
Summary
- Strings in JavaScript represent text data.
- Strings are immutable; they cannot be changed directly.
- JavaScript provides numerous string methods for manipulation.
- Template literals offer a convenient way to work with multi-line strings, interpolation, and expressions.
- Escape sequences allow you to represent special characters.
- String comparison is case-sensitive.